<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<script type="text/javascript">
    function getBase64Image(img,type) {
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, img.width, img.height);
        var dataURL = canvas.toDataURL("image/"+type);
        return dataURL;
    }

    function typeOfImg(source){
        var f=source.value;
        if(f=="")
        { alert("请上传图片");return false;}
        else
        {
            if(!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(f))
            {
                alert("图片类型必须是.gif,jpeg,jpg,png中的一种");
                return false;
            }
            else{
               var type= f.split('.')[1];//取图片后缀
               if(type=='jpg'||type=="JPG"){
                   type='jpeg'
               }
                showPreview(source,type)
            }
        }
    }

    function showPreview(source,type) {
        var file = source.files[0];
        if(window.FileReader) {
            var fr = new FileReader();
            fr.onloadend = function(e) {
                document.getElementById("portrait").src = e.target.result;
                var img = document.createElement('img');
                img.src =  e.target.result;
                img.onload =function() {
                    var data = getBase64Image(img,type);
                    console.log(data);
                }
            };
            fr.readAsDataURL(file);
        }
    }

</script>

<input type="file" name="file" onchange="typeOfImg(this);" />
<img id="portrait" src="" width="70" height="75">
</body>
</html>